package boot.controller.wxUser;

import boot.common.CommonResult;
import boot.domain.wxUser.WxUser;
import boot.model.WeChatModel;
import boot.model.wxResEntity;
import boot.service.wxUserService;
import boot.util.wxJwtUtil;
import boot.util.wxdecode;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;

/**
 * @author cb
 * @create 2022-09-13-17:22
 */
@CrossOrigin
@RestController
public class WxUserLogin {
    @Value("${wx.APPID}")
    String APPID;
    @Value("${wx.APPSECRET}")
    String APPSECRET;
    @Autowired
    private wxUserService wxUserService;
    @PostMapping("/login")
    public CommonResult login(@RequestBody WeChatModel weChatModel) {
        String iv = weChatModel.getIv();
        String encryptedData = weChatModel.getEncryptedData();
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APPID + "&secret=" + APPSECRET + "&js_code=" + weChatModel.getCode() + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
            String body = responseEntity.getBody();
            wxResEntity sessionData = JSON.parseObject(body, wxResEntity.class);
            String userInfo = wxdecode.decryptNew(encryptedData, sessionData.getSession_key(), iv);
            WxUser user = JSON.parseObject(userInfo, WxUser.class);
            user.setOpenid(sessionData.getOpenid());
            if(wxUserService.addUser(user)){
                String jwt = wxJwtUtil.createJWT(sessionData.toString());
                HashMap<String,String> map = new HashMap<>();
                map.put("token",jwt);
                return new CommonResult(200,"登录成功！",map);
            }
        }
        return new CommonResult(404,"登录失败！",null);
    }
}
